package com.zxf.service.impl;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;  
import redis.clients.jedis.SortingParams;  


import com.zxf.dao.UsersMapper;
import com.zxf.pojo.Messages;
import com.zxf.pojo.Params;
import com.zxf.pojo.Users;
import com.zxf.service.DistributionLock;
import com.zxf.service.UserService;
/**
 * @author 152
 *
 */
@Service  
//默认将类中的所有函数纳入事务管理.  
@Transactional  
public class UserServiceImpl implements UserService{

	
	 
	    @Autowired  
	    private UsersMapper userMapper;
	    
	    
	    @Resource  
	    private DistributionLock distributionLock; 
	    
	   // @Resource
		//public JedisClientSingle jedisClientSingle;
	    
	   
	    @Resource
	    protected RedisTemplate redisTemplate;
	    
	  //注入HashOperations对象
	    @Resource(name = "redisTemplate")
	    private HashOperations hashOps;
	  
	    //list
	    @Resource(name = "redisTemplate")
	    private ListOperations listOps;
	    
	  
	 public void insertUser(Users user,Map<String,Object> param) {  
	        //新增用户  
	        userMapper.insert(user);  
	 }

	public Users getId(int userid) {
		Users users = new Users();
		users = userMapper.selectByPrimaryKey(userid);
		return users;
	}

	public List getUserList() {
		// 用户列表
		List  userList = userMapper.getUserList();
		return userList;
	}

	public Map<String, Object> getUserList2() {
		// TODO Auto-generated method stub
		Map<String, Object> userMap = new HashMap<String, Object>();
		userMap= userMapper.getUserList2();
		return userMap;
	}

	public List getUserList3(int pagenum, int numbers) {
		// TODO Auto-generated method stub
		List userMap = new ArrayList();
		Params pams = new Params();
		pams.setPagenum(pagenum);
		pams.setPagesize(numbers);
		//userMap= userMapper.getUserList3(arguMap);
		userMap= userMapper.getUserList3(pams);
		return userMap;
	}

	public int getusertotle() {
		// 用户总数
		int totle = userMapper.gettotle();
		return totle;
	}

	public Users selectusers(Users users) {
		// TODO Auto-generated method stub
		return userMapper.selectusers(users);
	}

	//添加用户到redis
	public boolean add(Users users) {
		// TODO Auto-generated method stub
		Boolean result = true ;
		  saveUser(users);
		return result;
		
	}

	//删除用户到redis
	public void delete(int parseInt) {
		// TODO Auto-generated method stub
		
	}
	public void saveUser(final Users user) {
		String threadname ="用户加锁：";
		String  loginame= user.getLoginame().toLowerCase();
		Long timelock = distributionLock.lock(loginame, threadname);
		if(timelock<=0){
			//如果加锁不成功，说明给定的昵称已经被占用
			System.out.println("加锁失败，用户名已被暂用");
		}
		else{
			Map usermap = new HashMap();
			usermap.put("userid", user.getUserid());
			usermap.put("loginame", user.getLoginame());
			usermap.put("username", user.getUsername());
			usermap.put("following", String.valueOf(user.getFollowing()));
			usermap.put("followers", String.valueOf(user.getFollowers()));
			usermap.put("posts", String.valueOf(user.getPosts()));
			usermap.put("signup", user.getSignup());
			System.out.println(user.getLoginame());
			//用户信息放入list列表
			listOps.rightPush("users",user.getUserid());
			//用户详细信息放入hash散列表
			hashOps.putAll(user.getUserid(), usermap);
			//解锁
			distributionLock.unlock(loginame, timelock, threadname);
			
		}
		
		
		
		//iRedisDao.leftpush("user", user);
    }
//从redis取的用户信息
	@Override
	 /**
     * 根据key获取对象
     */
  

	public Users getuser(Users users) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Users selectByUsername(String username) {
		// TODO Auto-generated method stub
		return null;
	}

	
	
	 @Override
     public void add2(Users user) {
         // TODO Auto-generated method stub
         /*
          * boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
          * public Boolean doInRedis(RedisConnection redisConnection) throws
          * DataAccessException { RedisSerializer<String> redisSerializer =
          * redisTemplate .getStringSerializer(); byte[] key =
          * redisSerializer.serialize(user.getId()); byte[] value =
          * redisSerializer.serialize(user.getName()); return
          * redisConnection.setNX(key, value); } }); return result;
          */
         ValueOperations<String, Users> valueops = redisTemplate.opsForValue();
         valueops.set(user.getUserid().toString(), user);
     }


     @Override
     public Users getuser(String keyId) {
         ValueOperations<String, Users> valueops = redisTemplate.opsForValue();
         Users user = valueops.get(keyId);
         return user;
     }

	@Override
	public Users getUser(String key) {
		Map map = hashOps.entries(key);
		Users user = new Users();
		if(null != map.get("followers") && "" != map.get("followers")){
		user.setFollowers(Integer.parseInt(map.get("followers").toString()));
		}
		if(null != map.get("following") && "" != map.get("following")){
		user.setFollowing(Integer.parseInt(map.get("following").toString()));
		}
		if(null != map.get("posts") && "" != map.get("posts")){
		user.setPosts(Integer.parseInt(map.get("posts").toString()));
		}
		if(null != map.get("userid") && "" != map.get("userid")){
		user.setUserid(map.get("userid").toString());
		}
		if(null != map.get("signup") && "" != map.get("signup")){
		user.setSignup(map.get("signup").toString());
		}
		if(null != map.get("username") && "" != map.get("username")){
			user.setUsername(map.get("username").toString());
		}
		
		if(null != map.get("loginame") && "" != map.get("loginame")){
			user.setLoginame(map.get("loginame").toString());
		}
		
		
		return user;
	}

	@Override
	public void saveMessage(Messages message) {
		
			Map messagemap = new HashMap();
			Map messageidmap = new HashMap();
			messagemap.put("id", message.getId());
			messagemap.put("loginame", message.getLoginame());
			messagemap.put("message", message.getMessage());
			messagemap.put("posted", message.getPosted());
			messagemap.put("uid", message.getUid());
			System.out.println(message.getLoginame());
            //消息放入redis中的hash表
			hashOps.putAll(message.getId(), messagemap);
			//消息放入redis 的列表中供查询用
			messageidmap.put("id", message.getId());
			messageidmap.put("loginame", message.getLoginame());
			listOps.rightPush("message",messageidmap);
			Map map = hashOps.entries(message.getUid());
			int post =0;
			if(null != map.get("posts")){
				post=Integer.parseInt(map.get("posts").toString())+1;
			}
			
			//更新用户发布状态消息数量
			hashOps.put(message.getUid(),"posts", String.valueOf(post));
		
		
		
	}

	@Override
	public Messages  getmessage(String lowerCase) {
		Map map = hashOps.entries(lowerCase);
		Messages Message = new Messages();
		if(null != map.get("id") && "" != map.get("id")){
		Message.setId(map.get("id").toString());
		}
		if(null != map.get("loginame") && "" != map.get("loginame")){
		Message.setLoginame(map.get("loginame").toString());
		}
		if(null != map.get("message") && "" != map.get("message")){
		Message.setMessage(map.get("message").toString());
		}
		if(null != map.get("posted") && "" != map.get("posted")){
		Message.setPosted(map.get("posted").toString());
		}
		if(null != map.get("uid") && "" != map.get("uid")){
		Message.setUid(map.get("uid").toString());
		}
		return Message;
		
	}
 
	
	/**
	 * 从redis读取消息列表
	 */
	@Override
	public List getRedisMessagesList(int pageno, int pageSize) {
		// TODO Auto-generated method stub
		Map messageMap = new HashMap();
		List messagesList = new ArrayList();
		Messages messages = new Messages();
		//开始条数
				int startnum = (pageno-1)*pageSize;
				//结束条数
				int endnum =0;
				if(pageno==1){
					endnum = pageSize;
				}else{
					endnum =  (pageno-1)*pageSize;
				}
		List messagesidlist = listOps.range("message", startnum, endnum);
		if (null != messagesidlist && messagesidlist.size() > 0) {
			for (int i = 0; i < messagesidlist.size(); i++) {
				messageMap = (Map) messagesidlist.get(i);
				messages = getmessage(messageMap.get("id").toString());
				messagesList.add(messages);

			}
		} 

		return messagesList;
	}
	
	/**pageno 页码
	 * 从redis读取消息列表
	 * pageSize 页面数量
	 */
	@Override
	public List getRedisUserList(int pageno, int pageSize) {
		// TODO Auto-generated method stub
		List usersList = new ArrayList();
		Users users = new Users();
		//开始条数
		int startnum = (pageno-1)*pageSize;
		//结束条数
		int endnum =0;
		if(pageno==1){
			endnum = pageSize;
		}else{
			endnum =  (pageno-1)*pageSize;
		}
		 
		List useridlist = listOps.range("users", startnum, endnum);
		if (null != useridlist && useridlist.size() > 0) {
			for (int i = 0; i < useridlist.size(); i++) {
				users = getUser(useridlist.get(i).toString());
				usersList.add(users);

			}
		} 

		return usersList;
	}

	@Override
	public List getRedisMessagesList2(int start2, int pageSize2) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void saveMessage2(Messages message) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public int getRedisusertotle() {
		// TODO Auto-generated method stub
		return Integer.valueOf(listOps.size("users").toString());
	}

	@Override
	public int getRedistotle(String listname) {
		// TODO Auto-generated method stub
		return Integer.valueOf(listOps.size(listname).toString());
	}

	
	


	
}
